package cn.imvc.app.controllers;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.puff.cache.redis.Redis;

import cn.imvc.app.entities.Member;
import cn.imvc.app.entities.MemberRed;
import cn.imvc.app.entities.Red;
import cn.imvc.app.models.MemberModel;
import cn.imvc.app.models.MemberRedModel;
import cn.imvc.app.models.RedModel;
import cn.imvc.ipay.CommonWx;
import cn.imvc.ipay.Payment;
import me.hao0.wepay.core.Wepay;

@Controller
@RequestMapping("/red")
public class RedControllerImpl implements RedController {

	@Autowired
	private MemberModel memberModel;

	@Autowired
	private RedModel redModel;

	@Autowired
	private MemberRedModel memberRedModel;
	
	@Autowired
	Payment payment;
	
	@RequestMapping("/success.html")
	public String success(Model model, String token) {
		return "red/success";
	}

	@RequestMapping("/index.html")
	public String index(Model model, String token) {
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		List<MemberRed> memberRedList = null;
		if (member != null) {
			member = memberModel.get(member.getId());
			model.addAttribute("tx", member.getAvatar());
			memberRedList = memberRedModel.findAllRed(member.getId());
			if (memberRedList.size() > 0) {
				model.addAttribute("memberRedList", memberRedList);
			}

		}
		

		return "red/index";
	}
	
	@RequestMapping("/getTime.json")
	@ResponseBody
	public Map<String, Object> getTime() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Date begin=new Date();
		Date now = new Date();
		List<Red> redList = redModel.findByTime(now);
		now = new Date();
		if (redList.size() > 0) {
			resultMap.put("redId", redList.get(0).getId());
			Long time = (redList.get(0).getStartTime().getTime() - now.getTime());
			if (time < 0) {
				time = (long) 0;
			}
			resultMap.put("time1", time);
			if (redList.size() > 1) {
				time = (redList.get(1).getStartTime().getTime() - now.getTime());
				if (time < 0) {
					time = (long) 0;
				}
				resultMap.put("time2", time);
			}
		}
//		Date end=new Date();
		resultMap.put("com", now.getTime()-begin.getTime());
		return resultMap;
	}
	@RequestMapping("/check.json")
	@ResponseBody
	public Map<String, Object> check(Model model, String token, Integer redId) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "请先登录");
			return resultMap;
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		if (Redis.getInstance().setnx("Red" + token, "aa") != 1) {
			resultMap.put("code", "-2");
			resultMap.put("msg", "过于频繁");
			return resultMap;
		}
		Redis.getInstance().expire("Red" + token, 2);

		if (redId == null) {
			resultMap.put("code", "0");
			resultMap.put("msg", "没有活动");
			return resultMap;
		}

		if (member.getWxOpenid() == null || "".equals(member.getWxOpenid())) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请先关注公众号，绑定手机，才可以抢红包");
			return resultMap;
		}

		Red red = redModel.get(redId);
		Date now = new Date();
		if (red.getStartTime().after(now)) {
			resultMap.put("code", "0");
			resultMap.put("msg", "本次抢红包活动还没有开始");
			return resultMap;
		}
		if (red.getEndTime().before(now)) {
			resultMap.put("code", "2");
			resultMap.put("msg", "本次抢红包活动已经结束了，请期待下一次活动");
			return resultMap;
		}
		if (red.getMemberRed().size() >= red.getNum()) {
			resultMap.put("code", "3");
			resultMap.put("msg", "很遗憾，红包已发完");
			return resultMap;
		}
		resultMap = memberRedModel.sendRed(member, red);
		if(!"1".equals(resultMap.get("code"))){
			return resultMap;
		}
		
		try {
			
			MemberRed memberRed=(MemberRed) resultMap.get("memberRed");
			Wepay wepay = payment.getWxpay().getWepay();
			CommonWx common = new CommonWx(wepay);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("mch_billno", resultMap.get("billcode").toString());
			params.put("send_name", "星昊商城");
			params.put("re_openid", member.getWxOpenid());
			int perNum = red.getPerNum();
			if (perNum < 3) {
				perNum = 3;
			}
			int money = red.getAmount() / red.getNum() / 100;
			if (money < red.getPerNum()) {
				money = red.getPerNum();
			}
			params.put("total_amount", money * 100);
			params.put("total_num", perNum);
			params.put("amt_type", "ALL_RAND");
			params.put("wishing", red.getWishing());
			params.put("act_name", red.getTitle());
			params.put("remark", red.getRemark());
			
			Map<String, Object> result = common.sendToWx("https://api.mch.weixin.qq.com/mmpaymkttransfers/sendgroupredpack",
					params);
			if ("SUCCESS".equals(result.get("return_code")) && "SUCCESS".equals(result.get("result_code"))) {
				resultMap.put("code", "1");
				resultMap.put("msg", "成功");
				memberRed.setState(1);
				memberRed.setSureTime(new Date());
				memberRedModel.save(memberRed);
				Redis.getInstance().remove("RedId" + red.getId());
			} else {
				resultMap.put("code", "0");
				resultMap.put("msg", "发送失败");
				if(resultMap.get("memberRedId")!=null){
				memberRedModel.delete(Integer.parseInt(resultMap.get("memberRedId").toString()));
				}
				Redis.getInstance().remove("RedId" + red.getId());
			}
			
		} catch (Exception e) {
			if(resultMap.get("memberRedId")!=null){
				memberRedModel.delete(Integer.parseInt(resultMap.get("memberRedId").toString()));
				}
			Redis.getInstance().remove("RedId" + red.getId());
			resultMap.put("code", "0");
			resultMap.put("msg", "发送失败");
		}

		return resultMap;
	}

}
